<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户姓名" prop="customName">
        <el-input
          v-model="queryParams.customName"
          placeholder="请输入客户姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="地址" prop="avatar">
        <el-input
          v-model="queryParams.avatar"
          placeholder="请输入地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phoneNumber">
        <el-input
          v-model="queryParams.phoneNumber"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:custom:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:custom:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:custom:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:custom:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="customList"  stripe  border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="客户姓名" align="center" prop="customName" />
      <el-table-column label="手机号码" align="center" prop="phoneNumber" />
      <el-table-column label="客户类型" align="center" prop="customType" />
      <el-table-column label="客户分润占比%" align="center" prop="customAllocation" />
      <el-table-column label="所属省" align="center" prop="province" />
      <el-table-column label="所属市" align="center" prop="city" />
      <el-table-column label="地址" align="center" prop="avatar" />
      <el-table-column label="开通时间" align="center" prop="createTime" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分润查看" align="center" prop="customAllocation" >
        <template slot-scope="scope">
        <el-button type="primary" size="mini" @click="chatSharing(scope.row)">
          查看
        </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:custom:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:custom:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改客户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="750px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
        <el-form-item label="客户姓名" prop="customName">
          <el-input v-model="form.customName" placeholder="请输入客户姓名" />
        </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入手机号码" />
        </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
        <el-form-item label="客户类型" prop="customType">
          <el-select v-model="form.customType"
                     placeholder="请选择客户类型"
                     filterable
                     clearable>
            <el-option
              v-for="dict in typeOptions"
              :key="dict.customType"
              :label="dict.customType"
              :value="dict.customType">
            </el-option>
          </el-select>
        </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
        <el-form-item label="地址" prop="provinceId" >
          <el-select v-model="form.provinceId"
                     placeholder="省份"
                     filterable

                     @change="handleProvinceChange">
            <el-option
              v-for="dict in provinceList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id">
            </el-option>
          </el-select>
        </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left: -90px">
        <el-form-item  prop="cityId" >
          <el-select v-model="form.cityId"
                     placeholder="市"
                     filterable
                     >
            <el-option
              v-for="dict in cityList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id">
            </el-option>
          </el-select>
        </el-form-item>
          </el-col>
          <el-col :span="10">
        <el-form-item  prop="avatar" label-width="10px">
          <el-input v-model="form.avatar" placeholder="请输入地址" />
        </el-form-item>
          </el-col>
        </el-row>
<!--        <el-form-item label="绑定业务员" prop="bindUserId">-->
<!--          <el-select v-model="form.bindUserId"-->
<!--                     placeholder="请选择业务员"-->
<!--                     filterable-->
<!--                     clearable>-->
<!--            <el-option-->
<!--              v-for="item in userOptions"-->
<!--              :key="item.nickName"-->
<!--              :label="item.nickName"-->
<!--              :value="item.userId">-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->

<!--          <el-form-item label="logo" prop="logo">-->
<!--            <el-upload-->
<!--              class="avatar-uploader"-->
<!--              action="https://ydzs.mjunity.com/ydzs/system/enrollment/upload"-->
<!--              :show-file-list="false"-->
<!--              :on-success="handleAvatarSuccess"-->
<!--              :before-upload="beforeAvatarUpload"-->
<!--            >-->
<!--              <img  :src="form.logo" class="avatar" />-->
<!--            </el-upload>-->
<!--          </el-form-item>-->
        <el-row>
        <el-col :span="12">
          <el-form-item label="客户配置(%):" prop="customAllocation">
            <el-input-number v-model.number="form.customAllocation" placeholder="请输入客户配置" type="number" max="100" min="0"
                             ></el-input-number>
          </el-form-item>
        </el-col>
        </el-row>
        <el-button type="primary" @click="userSelect">添加分账人</el-button>
        <el-table  :data="userListChooes"  stripe  border >
          <el-table-column label="姓名" align="center" prop="nickName" />
          <el-table-column label="职位" align="center" prop="postName" />
          <el-table-column label="所属部门" align="center" prop="deptName" />
          <el-table-column prop="profitSharing" label="分润占比(%)" width="280" align="center">
            <template #default="scope" >
              <el-input-number v-model="scope.row.profitSharing" min="0" :max="100"  />
            </template>
          </el-table-column>
          <el-table-column align="center">
            <template slot-scope="scope">
              <el-button @click="removeUser(scope.row)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="userTitle" :visible.sync="userOpen" width="600px" append-to-body >
        <el-input
          v-model="queryParams2.nickName"
          placeholder="请输入客户姓名"
          clearable
          style="width: 220px"
          @keyup.enter.native="handleQuery2"
        />
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery2">搜索</el-button>
      <el-table  :data="userList"  stripe  border @selection-change="handleSelectionChangeUser">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="姓名" align="center" prop="nickName" />
        <el-table-column label="职位" align="center" prop="postName" />
        <el-table-column label="所属部门" align="center" prop="deptName" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="queding">确 定</el-button>
        <el-button @click="userCancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="sharingTitle" :visible.sync="sharingOpen" width="550px" append-to-body >
      <el-table  :data="chatSharingList"  stripe  border >
        <el-table-column label="姓名" align="center" prop="nickName" />
        <el-table-column label="职位" align="center" prop="postName" />
        <el-table-column label="分润占比(%)" align="center" prop="profitSharing" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="sharingCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCustom, getCustom, delCustom, addCustom, updateCustom } from "@/api/business/custom";
import {listUser, listUser2, listUsers} from "@/api/system/user";
import {listTypes} from "@/api/business/type";
import {getAreaList} from "@/api/business/scArea";
import {listSharings} from "@/api/business/sharing";

export default {
  name: "Custom",
  dicts: ['sr_customer_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      userOptions:[],
      provinceList: [],
      cityList: [],
      chatSharingList:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      sharingTitle: "用户分润占比",
      sharingOpen: false,
      // 总条数
      total: 0,
      // 客户信息表格数据
      customList: [],
      typeOptions:[],
      // 用户表格数据
      userList: [],
      //选择的
      userListChooes:[],
      //临时列表
      userListSelect:[],
      // 弹出层标题
      title: "",
      userTitle: "选择分润用户",
      userOpen: false,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customName: null,
        avatar: null,
        phoneNumber: null,
        userId: null,
        bindUserId: null,
        customType: null,
      },
      queryParams2: {

      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        customName: [
          { required: true, message: "客户姓名不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        phoneNumber: [
          { required: true, message: "电话不能为空", trigger: "blur" }
        ],
        avatar: [
          { required: true, message: "地址不能为空", trigger: "blur" }
        ],
        customType: [
          { required: true, message: "客户类型不能为空", trigger: "blur" }
        ],
        bindUserId: [
          { required: true, message: "绑定业务员ID不能为空", trigger: "blur" }
        ],
        provinceId: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        cityId: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getTypeLists();
    this.getArea();
    this.getUsersList();
  },
  methods: {
    removeUser(row){
      this.userListChooes.splice(this.userListChooes.indexOf(row), 1);
    },
    chatSharing(a){
      const custom = {};
      custom.customId = a.customId;
      this.chatSharingList = [];
      listSharings(custom).then(response => {
        this.chatSharingList = response.data;
        this.sharingOpen = true;
      })
    },
    getUsersList() {
      listUser2().then(response => {
          this.userList = response.data;
        }
      );
    },
    //上传前判断是不是jpg、png和图片大小不能超过2mb
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg' || 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/png 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    //上传图片成功
    handleAvatarSuccess (res, file) {
      this.form.logo = file.response.data
    },
    handleProvinceChange(value) {
      console.log('省份选择发生变化:', value);
      this.form.cityCode = '';
      this.fetchCities(value);
    },
    fetchCities(value) {
      const query = {};
      query.parentId = value;
      getAreaList(query).then(response => {
        this.cityList = response.data;
      })
    },
    getArea(){
      const query = {};
      query.level = 1;
      getAreaList(query).then(response => {
        this.provinceList = response.data;
      })
    },
    /** 查询客户信息列表 */
    getList() {
      this.loading = true;
      listCustom(this.queryParams).then(response => {
        this.customList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getTypeLists() {
      listTypes().then(response => {
        this.typeOptions = response.data;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.userListChooes = [];
      this.userListSelect = [];
    },
    userCancel(){
      this.userOpen = false;
    },
    sharingCancel(){
      this.sharingOpen = false;
    },
    // 表单重置
    reset() {
      this.userListChooes = [];
      this.userListSelect = [];
      this.form = {
        customId: null,
        customName: null,
        avatar: null,
        phoneNumber: null,
        userId: null,
        bindUserId: null,
        customType: null,
        createTime: null,
        updateTime: null,
        buSharingList: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleQuery2(){
      console.log("queryParams2",this.queryParams2)
      listUser2(this.queryParams2).then(response => {
        this.userList = response.data;
      })
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    getUserList() {
      listUsers().then(response => {
        console.log("success",response)
        this.userOptions = response.data;
      });
    },
    queding(){
      console.log("this.userListSelect",this.userListSelect)
      //遍历this.userListSelect添加，遍历this.userListChooes跳过与this.userListChooes重复的，不重复的添加进this.userListChooes
      for(let i=0;i<this.userListSelect.length;i++){
        let flag = true;
        for(let j=0;j<this.userListChooes.length;j++){
          if(this.userListSelect[i].userId === this.userListChooes[j].userId){
            flag = false;
            break;
          }
        }
        if(flag){
          this.userListChooes.push(this.userListSelect[i]);
        }
      }
      //清空选择器的状态
      this.userListSelect = [];
      // this.userListChooes = this.userListSelect;
      this.userOpen = false;
    },
    handleSelectionChangeUser(selection){
      console.log("selection",selection)
      this.userListSelect = selection;
      console.log("this.userListSelect",this.userListSelect)
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.customId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getUserList();
      this.open = true;
      this.title = "添加客户信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const customId = row.customId || this.ids
      getCustom(customId).then(response => {
        this.form = response.data;
        this.fetchCities(this.form.provinceId);
        this.getUserList();
        this.open = true;
        this.title = "修改客户信息";
      });
    },
    userSelect(){
      this.userOpen = true;
    },
    /** 提交按钮 */
    submitForm() {
      //console.log("+----+----++",this.userListChooes)
      this.form.buSharingList = this.userListChooes;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.customId != null) {
            updateCustom(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.userListChooes = [];
              this.userListSelect = [];
              this.open = false;
              this.getList();
            });
          } else {
            addCustom(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.userListChooes = [];
              this.userListSelect = [];
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const customIds = row.customId || this.ids;
      this.$modal.confirm('是否确认删除客户信息编号为"' + customIds + '"的数据项？').then(function() {
        return delCustom(customIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/custom/export', {
        ...this.queryParams
      }, `custom_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
